<template>
  <div class="add-product">
    <el-drawer
      v-model="modelValue"
      :before-close="cancelBind"
      class="common-drawerX"
      size="48.3%"
      :show-close="false"
      :lock-scroll="false"
    >
      <template #header>
        <div class="my-header">
          <div class="title">添加产品</div>
          <div class="titleRight" @click="cancelBind">
            <img src="@/assets/images/drawer_close.png" />
          </div>
        </div>
      </template>
      <div class="bind-content">
        <div class="sub-title">选择创建品类</div>
        <div class="search-input">
          <el-input
            v-model="queryParams.searchKey"
            placeholder="品类名称"
            :prefix-icon="Search"
            @input="checkSearch"
            clearable
          >
          </el-input>
          <div class="tree-content">
            <el-scrollbar max-height="498">
              <div class="tree-left">
                <div
                  class="tree-item"
                  v-for="(item, index) in categoryData"
                  :key="index"
                >
                  <div class="tree-parent" @click="openSecondChildren(item)">
                    <span>{{ item.name }}</span>
                    <span class="img"><img :src="item.src" /></span>
                  </div>
                  <div class="tree-children" v-show="item.open">
                    <div
                      :class="[
                        'children-item',
                        currentId == childItem.id ? 'active' : '',
                      ]"
                      v-for="(childItem, childIndex) in item.children"
                      :key="childIndex"
                      @click="clickSecondChildren(childItem)"
                    >
                      {{ childItem.name }}
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>

            <div class="tree-right">
              <span
                v-for="(item, index) in secondContent"
                :key="index"
                :class="[
                  'three-span',
                  selectSpan.id == item.id ? 'active' : '',
                ]"
                @click="handleSpanActive(item)"
                >{{ item.name }}</span
              >
            </div>
          </div>
        </div>
        <div class="sub-title">选择补充产品信息</div>
        <div class="form-content">
          <el-form
            :model="formModel"
            :rules="formRules"
            label-width="100px"
            ref="formRef"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="name">
                  <el-input
                    v-model="formModel.name"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入产品名称（1～30字符）"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品型号" prop="model">
                  <el-input
                    v-model="formModel.model"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入产品型号（1～30字符）"
                  ></el-input></el-form-item
              ></el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="品牌名称" prop="brand"
                  ><el-input
                    v-model="formModel.brand"
                    minlength="1"
                    maxlength="20"
                    placeholder="请输入品牌名称（1～20字符）"
                  ></el-input
                ></el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品牌英文" prop="brandEn"
                  ><el-input
                    v-model="formModel.brandEn"
                    minlength="1"
                    maxlength="30"
                    placeholder="请输入品牌英文（1～30字符）"
                  ></el-input></el-form-item
              ></el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelBind" class="btnCancer">取消</el-button>
          <el-button type="primary" @click="confirmBind" class="btnConfirm">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { productAdd, productTree } from "@/service/dp.ts";
const selectSpan: any = ref({});
const modelValue: any = ref(false);
const currentId: any = ref("");
const secondContent: any = ref([]);
const queryParams: any = ref({
  searchKey: "",
});
const formRef: any = ref(null);
const categoryData: any = ref([]);
watch(modelValue, (nv: any) => {
  if (nv) {
    productTree1();
  }
});
const formModel: any = ref({
  name: "",
  model: "",
  brand: "",
  brandEn: "",
});

const formRules: any = ref({
  name: [
    { required: true, message: "请输入产品名称" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
  ],
  model: [
    { required: true, message: "请输入产品型号" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
  ],
  brand: [
    { required: true, message: "请输入品牌名称" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符" },
  ],
  brandEn: [
    { required: true, message: "请输入品牌英文（1～30字符）" },
    { min: 1, max: 30, message: "长度在 1 到 30 个字符" },
  ],
});
const emit = defineEmits(["addSuccess"]);
// 返回本地图片地址
function getLocalImgurl(url: any) {
  return new URL(url, import.meta.url).href;
}

function openSecondChildren(val: any) {
  val.open = !val.open;
  if (val.open) {
    val.src = getLocalImgurl("../../../../assets/images/selected.png");
  } else {
    val.src = getLocalImgurl("../../../../assets/images/no_selected.png");
  }
}

async function productTree1() {
  let res: any = await productTree(queryParams.value);
  if (res.code === 200) {
    categoryData.value = res.data.map((item: any) => ({
      ...item,
      open: false,
      src: getLocalImgurl("../../../../assets/images/no_selected.png"),
    }));
  }
}

// 关闭之前
function cancelBind() {
  selectSpan.value = {};
  currentId.value = "";
  formRef.value.resetFields();
  secondContent.value = [];
  modelValue.value = false;
}

// 确定
async function confirmBind() {
  if (JSON.stringify(selectSpan.value) == "{}") {
    ElMessage.error("请选择品类");
    return;
  }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      let res: any = await productAdd({
        ...formModel.value,
        ...selectSpan.value,
        type: selectSpan.value.name,
      });
      if (res.code === 200) {
        ElMessage.success("添加成功");
        emit("addSuccess");
        cancelBind();
      } else {
        ElMessage.error(res.msg);
      }
    } else {
    }
  });
}

// 显示drawer
function showDrawer() {
  modelValue.value = true;
}

// 选择二级分类
function clickSecondChildren(val: any) {
  secondContent.value = val.children;
  currentId.value = val.id;
}

// 点击span
function handleSpanActive(item: any) {
  if (item.id != selectSpan.value.id) {
    formRef.value.resetFields();
  }
  selectSpan.value = item;
}

// 搜索
function checkSearch() {
  productTree1();
}

onMounted(() => {});

defineExpose({
  showDrawer,
});
</script>

<style scoped lang="scss">
.my-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  padding: 0 24px;
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    font-style: normal;
    text-transform: none;
  }
  .titleRight {
    img {
      cursor: pointer;
    }
  }
}
.bind-content {
  padding: 24px 0;
  .sub-title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 14px;
    color: #000000;
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    padding-left: 14px;
    height: 21px;
    border-left: 2px solid rgba(0, 0, 0, 0.9);
  }

  .search-input {
    margin-left: 16px;
    margin-top: 16px;
    margin-bottom: 24px;
  }
  .tree-content {
    margin-top: 8px;
    display: flex;
    justify-content: space-between;
    height: 500px;
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.1);
    .tree-left {
      width: 160px;
      height: 498px;
      background: #f6f6f6;
      .tree-item {
        .tree-parent,
        .children-item {
          padding-left: 16px;
          padding-right: 16px;
          height: 38px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          cursor: pointer;
          &.active {
            background: #ffffff;
            border-left: 3px solid #000000;
          }
        }
        .tree-parent {
          span {
            display: inline-block;
            &.img {
              width: 16px;
              height: 16px;
            }
          }
        }
      }
    }
    .tree-right {
      padding: 16px;
      flex: 1;
      .three-span {
        display: inline-block;
        width: 103px;
        height: 34px;
        line-height: 34px;
        text-align: center;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid rgba(0, 0, 0, 0.1);
        cursor: pointer;
        margin-right: 8px;
        margin-bottom: 8px;
        &.active {
          background: #000000;
          color: #ffffff;
        }
      }
    }
  }

  .form-content {
    margin-top: 16px;
  }
}
</style>
<style lang="scss">
.common-drawerX.el-drawer .el-drawer__header {
  padding: 0 !important;
  margin-bottom: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.common-drawerX.el-drawer .el-drawer__body {
  padding-top: 0;
  padding-bottom: 0;
}
.common-drawerX.el-drawer .el-drawer__footer {
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.common-drawerX.el-drawer {
  border: 1px solid rgba(0, 0, 0, 0.1);
  background: #ffffff;
}
</style>
